import 'package:flutter/services.dart';
import 'package:flutter_deer/index/iview/capital_comparison_list_iview.dart';
import 'package:flutter_deer/index/models/capital_comparison_entity.dart';
import 'package:flutter_deer/index/presenter/capital_comparison_list_presenter.dart';

import 'package:flutter_deer/index/provider/indicator_document_list_page_provider.dart';
import 'package:flutter_deer/index/provider/capital_comparison_page_provider.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/screen_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/index/models/indicator_document_entity.dart';
import 'package:flutter_deer/widgets/fadein_text.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:flutter_deer/widgets/my_refresh_list.dart';
import 'package:horizontal_data_table/horizontal_data_table.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:intl/intl.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';

class CapitalComparisonPage extends StatefulWidget {
  const CapitalComparisonPage({super.key});

  @override
  _CapitalComparisonPageState createState() => _CapitalComparisonPageState();
}

class _CapitalComparisonPageState extends State<CapitalComparisonPage>
    with
        BasePageMixin<CapitalComparisonPage, PowerPresenter>,
        TickerProviderStateMixin
    implements CapitalComparisonListIMvpView {
  final GlobalKey _bodyKey = GlobalKey();
  String _type  = '1';
  final HDTRefreshController _hdtRefreshController = HDTRefreshController();
  late CapitalComparisonListPagePresenter capitalComparisonListPagePresenter;
  CapitalComparisonListPageProvider provider =
      CapitalComparisonListPageProvider();
  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter =
        PowerPresenter<dynamic>(this);
    capitalComparisonListPagePresenter =
        new CapitalComparisonListPagePresenter();
    powerPresenter.requestPresenter([capitalComparisonListPagePresenter]);
    return powerPresenter;
  }

  @override
  void setCapitalComparisonPage(CapitalComparisonPageEntity? pageEntity) {
    provider.setCapitalComparisonItemPage(pageEntity);
  }

  @override
  void initState() {
    super.initState();
    // 强制横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    if (mounted) {
      _onRefresh();
    }
  }

  @override
  void dispose() {
    // provider.dispose();
    super.dispose();
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  }

  @override
  Widget build(BuildContext context) {
    final Color? iconColor = ThemeUtils.getIconColor(context);

    return ChangeNotifierProvider<CapitalComparisonListPageProvider>(
        create: (_) => provider,
        child: Consumer<CapitalComparisonListPageProvider>(
            builder: (_, provider, child) {

          return Scaffold(
              key: _bodyKey,
              appBar: AppBar(
                  leading: IconButton(
                    onPressed: () async {
                      FocusManager.instance.primaryFocus?.unfocus();
                      final isBack = await Navigator.maybePop(context);
                      if (!isBack) {
                        await SystemNavigator.pop();
                      }
                    },
                    tooltip: '${DeerLocalizations.of(context)!.back.nullSafe}',
                    padding: EdgeInsets.all(12.0),
                    icon: Image.asset(
                      Constant.backImg,
                      color: ThemeUtils.getIconColor(context),
                      height: 24,
                      width: 24,
                    ),
                  ),
                  title: Text('项目年度资金对比',
                      style: TextStyle(
                        fontSize: Dimens.font_sp18,
                        color:
                            context.isDark ? Colours.text_gray : Colours.text,
                      )),
                  actions: <Widget>[
                    TextButton(

                      onPressed: () => _showFilterBottomSheet(context),
                      child: Text(
                        '筛选',
                        style: TextStyle(color: Colors.black), // 根据需要设置文字颜色
                      ),
                    ),
                  ]),
              body: provider.list!.length > 0
                  ? Padding(
                    padding:EdgeInsets.all(20),
                    child: (
                        getDeerListView(provider)
                      ),
                    )   
                  : Container(
                      width: MediaQuery.of(context).size.width,
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Lottie.asset('assets/lottie/no_football_game.json',
                                width: MediaQuery.of(context).size.width / 3,
                                fit: BoxFit.cover),
                            Gaps.vGap8,
                            FadeInText(
                                text:'暂无数据')
                          ],
                        ),
                      ),
                    ));

        }));
        
  }




  
  HorizontalDataTable getDeerListView(
      CapitalComparisonListPageProvider provider) {
    int leftHeadCount = 1;
    List<String> headers = [
      '项目名称',
      '本年支出',
      '上年支出',
      '同比增减额',
      '增减比例',
    ];
    List<String> columns = [
      'dep_bgt_eco_name',
      'amt1',
      'amt2',
      'amt_period',
      'radio'
    ];

    List<Container> headContainers = [];
    List<double> rightWidths = [];
    List<double> leftWidths = [];
    double rightWidth = 0;
    double leftWidth = 0;
    for (int i = 0; i < headers.length; i++) {
      double headWidth = Screen.calculateTextWidth(
              context, headers.elementAt(i), FontWeight.bold, 12, 300, 1) +
          10;
      if (i < leftHeadCount) {
        leftWidth += headWidth;
        leftWidths.add(headWidth);
      } else {
        rightWidth += headWidth;
        rightWidths.add(headWidth);
      }
      headContainers.add(Container(
        width: headWidth,
        height: 56,
        padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
        alignment: Alignment.centerLeft,
        child: Text(headers.elementAt(i),
            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12)),
      ));
    }
    return HorizontalDataTable(
      leftHandSideColumnWidth: leftWidth,
      rightHandSideColumnWidth: rightWidth,
      isFixedFooter: false,
      isFixedHeader: true,
      headerWidgets: headContainers,
      footerWidgets: headContainers,
      leftHandSideColBackgroundColor: const Color(0xFFFFFFFF),
      rightHandSideColBackgroundColor: const Color(0xFFFFFFFF),
      enablePullToRefresh: true,
      refreshIndicator: const WaterDropHeader(),
      enablePullToLoadNewData: true,
      loadIndicator: const ClassicFooter(),
      htdRefreshController: _hdtRefreshController,
      onLoad: _loadMore,
      onRefresh: _onRefresh,
      rowSeparatorWidget: const Divider(
        color: Colors.black38,
        height: 1.0,
        thickness: 0.0,
      ),
      itemCount: provider.list!.length,
      leftSideItemBuilder: (context, index) {
        CapitalComparisonEntity doc = provider.list!.elementAt(index);
        List<Container> cells = [];
        final List<String> _keyList = ['dep_bgt_eco_name', 'gov_bgt_eco_name', 'exp_func_name', 'agency_name', 'fund_type_name'];
        for (int i = 0; i < leftWidths.length; i++) {
          cells.add(Container(
            width: leftWidths.elementAt(i),
            height: 52,
            padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
            alignment: Alignment.center,
            child: Text(
              doc.toJson()[_keyList[int.parse(_type) - 1]].toString(),
              style: TextStyle(fontSize: 10),
            ),
          ));
        }
        return Row(
          children: cells,
        );
      },
      rightSideItemBuilder: (context, index) {
        CapitalComparisonEntity doc = provider.list!.elementAt(index);
        List<Container> cells = [];
        for (int i = 0; i < rightWidths.length; i++) {
          bool containsWord = columns[leftHeadCount + i].contains("amt");
          final numString = doc.toJson()[columns[leftHeadCount + i]] != null ? doc.toJson()[columns[leftHeadCount + i]] : '0.00';
          final formatNum = containsWord ? NumberFormat.decimalPattern('en_us').format(double.parse(numString.toString())) : numString;
          final result = formatNum == '0' ? '0.00' : formatNum;
          cells.add(Container(
            width: rightWidths.elementAt(i),
            height: 52,
            padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
            alignment: Alignment.center,
            child: Text(
              result.toString(),
              style: TextStyle(fontSize: 10),
            ),
          ));
        }
        return Row(
          children: cells,
        );
      },
    );
  }

  Future<dynamic> _onRefresh() async {
    Future.delayed(Duration(seconds: 1), () {
      capitalComparisonListPagePresenter.getCapitalComparisonList('2022', '1');
      _hdtRefreshController.loadComplete();
    });
  }

  Future<dynamic> _loadMore() async {
    Future.delayed(Duration(seconds: 1), () {
      capitalComparisonListPagePresenter.getMoreCapitalList(
          '2022', provider.currentPage! + 1, '1');
      _hdtRefreshController.refreshCompleted();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
  Future<void> _showFilterBottomSheet(BuildContext context) async {
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            ListTile(
              title: Text('部门支出经济分类预算年份支出费用同比'),
              onTap: () {
                Navigator.pop(context);
                _type = '1';
                capitalComparisonListPagePresenter.getCapitalComparisonList('2022', '1');
                _hdtRefreshController.loadComplete();
              },
            ),
            ListTile(
              title: Text('政府支出经济分类预算年份支出费用同比'),
              onTap: () {
                Navigator.pop(context);
                _type = '2';
                capitalComparisonListPagePresenter.getCapitalComparisonList('2022', '2');
                _hdtRefreshController.loadComplete();
              },
            ),
            ListTile(
              title: Text('支出功能预算年份支出费用同比'),
              onTap: () {
                Navigator.pop(context);
                _type = '3';
                capitalComparisonListPagePresenter.getCapitalComparisonList('2022', '3');
                _hdtRefreshController.loadComplete();
              },
            ),
            ListTile(
              title: Text('单位预算年份支出费用同比'),
              onTap: () {
                Navigator.pop(context);
                 _type = '4';
                capitalComparisonListPagePresenter.getCapitalComparisonList('2022', '4');
                _hdtRefreshController.loadComplete();
              },
            ),
            ListTile(
              title: Text('资金性质预算年份支出费用同比'),
              onTap: () {
                Navigator.pop(context);
                 _type = '5';
                capitalComparisonListPagePresenter.getCapitalComparisonList('2022', '5');
                _hdtRefreshController.loadComplete();
              },
            ),
          ],
        );
      },
    );
  }


  @override
  bool get wantKeepAlive => false;
}
